package com.shanghaionstar.activity.webview.handler;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;

import com.onstar.cn.ShareEntity;
import com.onstar.cn.common.jsBridge.BridgeHandler;
import com.onstar.cn.common.jsBridge.BridgeWebView;
import com.onstar.cn.common.jsBridge.CallBackFunction;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.BitmapUtil;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.UserInfo;
import com.onstar.cn.mag.UserLocation;
import com.onstar.cn.mag.VehicleInfo;
import com.onstar.cn.mag.WebViewQueryResult;
import com.onstar.cn.smart.entity.ServiceItem;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.activity.webview.handler.bean.AppInfoEntity;
import com.shanghaionstar.activity.webview.handler.bean.ShareDialogResonse;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.login.LoginActivity;
import com.shanghaionstar.nav.share.ShareImgDialog;
import com.shanghaionstar.user.SettingFragment;
import com.shanghaionstar.user.service.OptService;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.H5JSObject;
import com.shanghaionstar.utils.LoadCityList;
import com.shanghaionstar.utils.NavHolder;
import com.shanghaionstar.utils.UrlToBitmapTask;
import com.shanghaionstar.weight.TopLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by onstarios on 2017/6/19.
 * 注册h5方法类
 */

public class WebBridgeHelper {

    CommonWebViewActivity mContext;

    public String getBackFunId() {
        return backFunId;
    }

    public void setBackFunId(String backFunId) {
        this.backFunId = backFunId;
    }

    private String backFunId;

    BridgeWebView mWebView;

    public WebBridgeHelper(CommonWebViewActivity mContext) {
        this.mContext = mContext;
    }

    public void registerCommonHandler(final BridgeWebView webview) {
        mWebView = webview;

        webview.registerHandler("getToken", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                function.onCallBack(ApplicationUtil.getInstance().getToken());
            }
        });

        webview.registerHandler("query", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                if (data != null) {
                    List<String> datas = Arrays.asList(data.split(","));
                    UserInfo userInfo = new UserInfo();
                    VehicleInfo vehicleInfo = new VehicleInfo();
                    UserLocation userLocation = new UserLocation();
                    if (datas.contains("userInfo")) {
                        userInfo.idpid = ApplicationUtil.getInstance().getIdpID();
                        userInfo.isLogin = ApplicationUtil.getInstance().isLogin() ? "1" : "0";
                        userInfo.role = ApplicationUtil.getInstance().getLoginRole();
                    }
                    if (datas.contains("vehicleInfo")) {
                        vehicleInfo.brand = ApplicationUtil.getInstance().getCarInfo();
                        vehicleInfo.engineNumber = PreferencesUtls.getInstance(mContext).getString("engineNumber", "");
                        vehicleInfo.isEV = ApplicationUtil.getInstance().isPhev() ? "1" : "0";
                        vehicleInfo.isGen10 = ApplicationUtil.getInstance().isGen10() ? "1" : "0";
                        vehicleInfo.licensePlate = PreferencesUtls.getInstance(mContext).getString("plateNumber", "");
                        vehicleInfo.vin = ApplicationUtil.getInstance().getVin();
                    }

                    if (datas.contains("userLocation")) {
                        String city = NavHolder.getInstance(mContext).getCurrentCity();
                        String cityCode = "";
                        userLocation.city = city;
                        if (!CommonUtil.isNull(city)) {
                            if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
                                LoadCityList cityList = new LoadCityList(mContext);
                                cityCode = cityList.findByEnCity(city);
                            }
                        }
                        userLocation.cityCode = cityCode;
                        if (NavHolder.getInstance(mContext).getMyLocation() != null) {
                            userLocation.latitude = String.valueOf(NavHolder.getInstance(mContext).getMyLocation().getLatitude());
                            userLocation.longitude = String.valueOf(NavHolder.getInstance(mContext).getMyLocation().getLongitude());
                        }
                        userLocation.province = NavHolder.getInstance(mContext).getCurrentProvince();
                    }
                    final WebViewQueryResult webViewQueryResult = new WebViewQueryResult();
                    webViewQueryResult.setUserInfo(userInfo);
                    webViewQueryResult.setUserLocation(userLocation);
                    webViewQueryResult.setVehicleInfo(vehicleInfo);

                    if (datas.contains("serviceInfo") && ApplicationUtil.getInstance().isLogin()) {
                        mContext.setLoading(true);
                        OptService optService = new OptService(mContext);
                        optService.getServiceStatus("").subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<List<ServiceItem>>() {
                                    @Override
                                    public void call(List<ServiceItem> items) {
                                        mContext.setLoading(false);
                                        if (items != null) {
                                            ApplicationUtil.getInstance().setServiceItems(items);
                                            jsCallBack(webViewQueryResult, function);
                                        }
                                    }
                                }, new Action1<Throwable>() {
                                    @Override
                                    public void call(Throwable throwable) {
                                        mContext.setLoading(false);
                                        jsCallBack(webViewQueryResult, function);
                                    }
                                });
                    } else {

                        jsCallBack(webViewQueryResult, function);
                    }
                }

            }
        });

        webview.registerHandler("openCalendar", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                H5JSObject h5JSObject = new H5JSObject(mContext);
                h5JSObject.setWebView(webview);
                h5JSObject.openCalendar("");
            }
        });

        webview.registerHandler("showDemoShareOrDialog", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                final ShareDialogResonse resonse = GsonHelper.fromJson(data, ShareDialogResonse.class);
                if ("pop".equals(resonse.getType())) {
                    new ShareNotAllowDialog(mContext, resonse.getContent(), resonse.getBtnText()).show();
                } else if ("settingPop".equals(resonse.getType())) {
                    new ShareNotAllowDialog(mContext, resonse.getContent(), resonse.getBtnText(), new ShareNotAllowDialog.OnClickBtnListener() {
                        @Override
                        public void onClickBtn() {
                            //go to settig page;
                            Intent intent = new Intent(mContext, MoreActivity.class);
                            intent.putExtra(FinalConstants.JUMP_FLAG, SettingFragment.class.getName());
                            mContext.startActivity(intent);
                            mContext.finish();
                        }
                    }).show();
                }
                if (resonse != null && "sharePop".equals(resonse.getType())) {

                    mContext.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mContext.getTop_layout().setOnRightTextClickLstener(mContext.getString(R.string.share), new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new ShareNotAllowDialog(mContext, resonse.getContent(), resonse.getBtnText()).show();
                                }
                            });
                            mContext.getTop_layout().showRightButton(true);
                        }
                    });
                }
            }
        });


        webview.registerHandler("close", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mContext.finish();
            }
        });

        webview.registerHandler("goHomePage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mContext.setResult(LoginActivity.REQUEST_VERIFY_INFO3);
                mContext.finish();
                BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.LoginVerificationSuccess_ClickAPPHome.getStringValue());
            }
        });


        new CommonWebShareHelper(mContext).registerHandler(mContext.getTop_layout(), webview);

        webview.registerHandler("returnFunctionId", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    backFunId = "";
                } else {
                    try {
                        JSONObject obj = new JSONObject(data);
                        backFunId = obj.getString("param");
                    } catch (JSONException e) {
                        LogManager.getInstance().e(e);
                    } catch (Exception e) {
                        LogManager.getInstance().e(e);
                    }
                }
            }
        });

        webview.registerHandler("openCamera", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mContext.openCamera(mContext);
            }
        });

        webview.registerHandler("callPhone", new BridgeHandler() {
            @Override
            public void handler(final String data, CallBackFunction function) {
                mContext.requestRunTimePermissions(new String[]{Manifest.permission.CALL_PHONE}, new PermissionCall() {
                    @Override
                    public void requestSuccess() {
                        if (!CommonUtil.isNull(data)) {
                            ShareEntity shareEntity = GsonHelper.fromJson(data, ShareEntity.class);
                            if (!CommonUtil.isNull(shareEntity)) {
                                H5JSObject h5 = new H5JSObject(mContext);
                                h5.dial(shareEntity.getPhone());
                            }
                        }
                    }

                    @Override
                    public void refused() {

                    }

                });
            }
        });

        /**
         * 油耗排名分享
         */
        webview.registerHandler("screenshotShare", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        final TopLayout topLayout = mContext.getTop_layout();
                        topLayout.setOnRightTextClickLstener(mContext.getString(R.string.share), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Bitmap bitmap = BitmapUtil.webViewShot(mWebView);
                                showShareDialog(bitmap);
                            }
                        });
                        topLayout.showRightButton(true);
                    }

                });
            }
        });


        /**
         * 油耗水平小贴士分享
         */
        webview.registerHandler("shareImage", new BridgeHandler() {
            @Override
            public void handler(final String data, CallBackFunction function) {
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        final TopLayout topLayout = mContext.getTop_layout();
                        topLayout.setOnRightTextClickLstener(mContext.getString(R.string.share), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                UrlToBitmapTask imageTask = new UrlToBitmapTask(mContext, data);
                                imageTask.execute();
                            }
                        });
                        topLayout.showRightButton(true);
                    }

                });
            }
        });


        //爱车评估获取版本信息
        webview.registerHandler("getAppInfo", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                DeviceUtil util = new DeviceUtil(mContext);
                AppInfoEntity appInfoEntity = new AppInfoEntity();
                appInfoEntity.setVersion(util.getAppVersion());//获取版本号
                appInfoEntity.setDevice("android");

                //转成json字符串
                String jsonStr = GsonHelper.toJson(appInfoEntity);
                function.onCallBack(jsonStr);
            }
        });
    }

    private void jsCallBack(WebViewQueryResult webViewQueryResult, CallBackFunction function) {
        webViewQueryResult.setServiceInfo(ApplicationUtil.getInstance().getServiceItems());
        String jsonToH5 = GsonHelper.toJson(webViewQueryResult);
        LogManager.getInstance().d(jsonToH5);
        function.onCallBack(jsonToH5);
    }


    private void showShareDialog(Bitmap bitmap) {
//        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.DiagnosticsShare.getStringValue());
        ShareImgDialog dialog = new ShareImgDialog(mContext, R.style.Theme_Transparent);
        dialog.setShareBitmap(bitmap);
//        dialog.setReportCancel(FunctionNameFindId.DiagShare_Cancel.getStringValue());
//        dialog.setMoments(FunctionNameFindId.DiagShare_Moments.getStringValue());
//        dialog.setWechat(FunctionNameFindId.DiagShare_Wechat.getStringValue());
        dialog.show();
    }
}
